/*******************************************************************************

 * Copyright (c) 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Ali Ok (www.aliok.info) - initial API and implementation
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.team.internal.search;


import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.history.IFileHistory;
import org.eclipse.team.core.history.IFileHistoryProvider;
import org.eclipse.team.core.history.IFileRevision;

/**
 * Visitor for searching a particular string in the commit comments of resources.
 * @author Ali Ok
 *
 */
//package private, wont be used elsewhere
final class SearchVisitor implements IResourceVisitor {
		private final IFileHistoryProvider fhp;
		private final IProgressMonitor monitor;
		private SearchResult searchResult;
		private String searchText;

		/**
		 * @param fhp <code>IFileHistoryProvider</code> for the project of resource.
		 * @param monitor 
		 * @param searchResult SearchResult to add matches 
		 * @param text Search string
		 */
		public SearchVisitor(IFileHistoryProvider fhp,
				IProgressMonitor monitor, SearchResult searchResult, String text) {
			this.fhp = fhp;
			this.monitor = monitor;
			this.searchResult = searchResult;
			this.searchText = text;
		}


		public boolean visit(IResource resource) throws CoreException {
			//assumed each resource is 1 unit of work
			//TODO: externalize
			monitor.setTaskName("Getting file history of " + resource.getName());	
			IFileHistory fh = fhp.getFileHistoryFor(resource,
					IFileHistoryProvider.NONE, monitor);
			if (fh != null) {
				IFileRevision[] revisions = fh.getFileRevisions();
				for (int j = 0; j < revisions.length; j++) {
					String comment = revisions[j].getComment();
					// TODO: add proper matching
					if (comment != null && comment.matches(".*" + searchText + ".*")) {
						searchResult.add(revisions[j], fh);
					}

				}
			}
			monitor.worked(1);
			if (resource.getType() == IResource.FILE) {
				return false;
			}
			return true;
		}
	}